package com.example.idlefish.MyAccount.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.CreateGoodActivityContract
import com.example.idlefish.GoodsInfo.pojo.QueryGoodResponse
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.CommonUtil
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.R
import com.example.idlefish.databinding.MyaccountPurchasedBinding
import com.example.idlefish.databinding.MyaccountSoldBinding
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException

class MyPurchasedActivity : AppCompatActivity()  {
    private lateinit var binding: MyaccountPurchasedBinding
    private var index = -1
    private var position = -1
    private val client = OkHttpClient()
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()
    private val mapper = ObjectMapper()
    private var myPurchasedGoodsList = ArrayList<GoodWithUser>()
    private var adapter = MyPurchasedAdapter(myPurchasedGoodsList)


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = MyaccountPurchasedBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(findViewById(R.id.toolbar))
        supportActionBar?.setDisplayHomeAsUpEnabled(true);// 添加默认的返回图标
        supportActionBar?.setHomeButtonEnabled(true); // 设置返回键可用

        binding.loading.show()
        val userInfo = CommonUtil.getSerializable(intent, "userHomepageInfo", UserHomepageInfo::class.java)

        // 列表
        initList(UserConst.id)

        setSupportActionBar(binding.toolbar)

        val layoutManager = LinearLayoutManager(this)
        binding.myPurchasedList.layoutManager = layoutManager
        binding.myPurchasedList.adapter = adapter

        binding.myPurchasedEnd.setOnClickListener{
            createGoodActivityLauncher.launch(Unit)
        }
    }

    private val createGoodActivityLauncher = registerForActivityResult(CreateGoodActivityContract()) { result ->

    }

    private fun initList(id: Long) {
        binding.loading.show()
        try {
            val request = Request.Builder().url(NetworkSettings.USER + "queryMyPurchasedList?id=${id}")
                .get().build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val gson = Gson()
                    val responseData = response.body?.string()
                    Log.i("查看我买到的的", responseData.toString())

                    val data = gson.fromJson(responseData, GoodWithUserResult::class.java)
                    val info = data.data

                    handler.post {
                        if (info != null) {
                            myPurchasedGoodsList.addAll(info)
                        }
                        adapter.notifyDataSetChanged()
                        Log.i("购买列表", "$myPurchasedGoodsList.")
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
        binding.loading.hide()
    }

    private val homepageLauncher = registerForActivityResult(HomepageContract()) { result ->

    }

    private inner class MyPurchasedAdapter(private val myPurchasedList: ArrayList<GoodWithUser>) :
        RecyclerView.Adapter<MyPurchasedAdapter.ViewHolder>() {
        // 创建ViewHolder实例，我们在这个方法中将elem布局加载进来，
        // 创建一个ViewHolder实例，并把加载出来的布局传入构造函数当中，最后将ViewHolder的实例返回。
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.myaccount_purchased_elem, parent, false)
            val viewHolder = ViewHolder(view)

            // 单击元素
            viewHolder.itemView.setOnClickListener {
                val position = viewHolder.absoluteAdapterPosition
                val goodInfo = myPurchasedList[position]
                index = position

                Toast.makeText(parent.context, "点击了${goodInfo.info}", Toast.LENGTH_SHORT).show()

            }

            // 删除
            /*            viewHolder.deleteButton.setOnClickListener {
                            position = viewHolder.absoluteAdapterPosition
                            delete(myPurchasedGoodsList[position].trainId!!)
                            myPurchasedGoodsList.removeAt(position)
                            notifyItemRemoved(position)
                        }*/
            return viewHolder
        }

        // RecyclerView 子项的最外层布局
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val avatar: ImageView = view.findViewById(R.id.myPurchased_avatar)
            val nickname: TextView = view.findViewById(R.id.myPurchased_nickname)
            val image: ImageView = view.findViewById(R.id.myPurchased_image)
            val info: TextView = view.findViewById(R.id.myPurchased_info)
            val price: TextView = view.findViewById(R.id.myPurchased_price)


            /*    val deleteButton: Button = view.findViewById(R.id.button_delete)*/
        }

        // 对 RecyclerView 子项的数据进行赋值，会在每个子项被滚动到屏幕内的时候执行
        // 通过 position参数得到当前项的info实例，然后再将数据设置到ViewHolder的TextView当中即可
        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val good = myPurchasedList[position]
            // 卖家
            holder.avatar.setImageBitmap( ApplicationConst.decodeBase64ToImage(applicationContext, good.avatar))
            holder.nickname.text = good.nickname

            // 商品
            if (good.pic != null) {
                holder.image.setImageBitmap(ApplicationConst.decodeBase64ToImage(applicationContext,
                    good.pic!!
                ))
            } else {
                holder.image.setImageResource(R.drawable.defualt_image)
            }
            holder.info.text = good.info
            holder.price.text = "¥${good.price}"
        }

        override fun getItemCount() = myPurchasedList.size

    }




    fun back(view: View) {
        finish()
    }

}